package com.kong.meirimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.kong.common.constant.ProductConstant;
import com.kong.common.to.SkuReductionTo;
import com.kong.common.to.SpuBoundTo;
import com.kong.common.to.es.SkuEsModel;
import com.kong.common.utils.R;
import com.kong.common.vo.SkuHasStockVo;
import com.kong.meirimall.product.entity.*;
import com.kong.meirimall.product.feign.CouponFeignService;
import com.kong.meirimall.product.feign.SearchFeignService;
import com.kong.meirimall.product.feign.WareFeignService;
import com.kong.meirimall.product.service.*;
import com.kong.meirimall.product.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kong.common.utils.PageUtils;
import com.kong.common.utils.Query;

import com.kong.meirimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional            //因为要保存很多东西，这是一个事务
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 1、保存 spu 基本信息；pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);
        // 2、保存 spu 的描述图片 到 pms_spu_info_desc 表
            // spu_id 不是自增的，要拿来
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity infoDescEntity = new SpuInfoDescEntity();
        infoDescEntity.setSpuId(spuInfoEntity.getId());
        infoDescEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuInfoDesc(infoDescEntity);
        // 3、保存 spu 的图片集；pms_spu_images
        List<String> images = spuSaveVo.getImages();
            //保存图片之前，还要知道是给哪个商品的，传入参数 spu 的 id
        spuImagesService.saveImages(spuInfoEntity.getId(),images);
        // 4、保存 spu 的规格参数；pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> attrValueEntities = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            Long attrId = attr.getAttrId();
            attrValueEntity.setAttrId(attrId);
            //页面没提交 attrName ，需要查
            attrValueEntity.setAttrName(attrService.getById(attrId).getAttrName());
            attrValueEntity.setAttrValue(attr.getAttrValues());
            attrValueEntity.setQuickShow(attr.getShowDesc());
            attrValueEntity.setSpuId(spuInfoEntity.getId());
            return attrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(attrValueEntities);
        // 5、保存 spu 的积分信息；跨库：sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r1 = couponFeignService.saveSpuBounds(spuBoundTo);
        if(r1.getCode()==0){
            log.error("远程保存 sku 优惠信息失败");
        }

        // 6、保存 当前 spu 对应的所有 sku 信息；
        List<Skus> skus = spuSaveVo.getSkus();
        if(skus !=null && skus.size()>0){
            skus.forEach(sku -> {
                //   1）、sku 的基本信息；pms_sku_info
                //遍历 sku 中的每个图片，判断哪个是默认图片
                String defaultImg = "";
                for (Images img : sku.getImages()) {
                    if(img.getDefaultImg()==1){
                        defaultImg=img.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);
                //将 skuInfoEntity 保存到数据库后，才能从库中取得自动生成的 skuId，拼装 图片对象(一个 sku 的所有图片对象的 skuId 同)
                Long skuId = skuInfoEntity.getSkuId();
                //   2）、sku 的图片信息；pms_sku_images
                //      TODO 没有图片路径的无需保存（没选中的）
                List<SkuImagesEntity> imagesEntities = sku.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity->{
                    //返回 false 就会被过滤掉
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);
                //   3）、sku 的销售属性信息；pms_sku_sale_attr_value
                List<Attr> attrs = sku.getAttr();
                List<SkuSaleAttrValueEntity> saleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValue = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValue);
                    skuSaleAttrValue.setSkuId(skuId);
                    return skuSaleAttrValue;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(saleAttrValueEntities);
                //   4）、sku 的优惠、满减等信息；跨库：sms_sku_ladder、sms_sku_full_reduction、sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if(skuReductionTo.getFullCount()>0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal(0))==1){
                    R r = couponFeignService.saveSkuReduction(skuReductionTo);
                    if(r.getCode()!=0){
                        log.error("远程保存 spu 积分信息失败");
                    }
                }
            });

        }

    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<SpuInfoEntity>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id", brandId);
        }
        String catalogId = (String) params.get("catalogId");
        if(!StringUtils.isEmpty(catalogId) && !"0".equalsIgnoreCase(catalogId)){
            wrapper.eq("catalog_id",catalogId);
        }
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    // 商品上架
    @Override
    public void up(Long spuId) {
        //存储需要上架的商品
        List<SkuEsModel> upProducts=new ArrayList<>();
        //1、组装需要的数据
        SkuEsModel esModel = new SkuEsModel();
        // 查询当前  sku 的所有规格属性信息（只需要 可以被检索的）
        // 所有实体 -> 所有 attrId -> 用 xml 查出符合要求的 attrId -> 用符合要求的 attrId 过滤出 符合要求的实体
        List<ProductAttrValueEntity> attrValueEntities = productAttrValueService.baseAttrListforspu(spuId);
        List<Long> attrIds = attrValueEntities.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        // 过滤出可被检索且 在 查出来的 attrIds 中的数据
        List<Long> searchAttrIds=attrService.selectSearchAttrs(attrIds);
        Set<Long> idSet=new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> attrs = attrValueEntities.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());
        //  查出当前 spuId 对应的所有 sku 信息，并转为 传入 es 的模型
        List<SkuInfoEntity> skuInfoEntities=skuInfoService.getSkusBySpuId(spuId);
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //发送远程调用，库存系统查询是否有库存
        Map<Long, Boolean> booleanMap=null;
        try{
            R hasStock = wareFeignService.getSkusHasStock(skuIds);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            booleanMap = hasStock.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
        }catch (Exception e){
            log.error("库存服务查询异常：原因{}",e);
        }
        Map<Long, Boolean> finalBooleanMap = booleanMap;
        upProducts = skuInfoEntities.stream().map(skuInfo -> {
            SkuEsModel esModel1 = new SkuEsModel();
            BeanUtils.copyProperties(skuInfo,esModel1);
            esModel1.setSkuPrice(skuInfo.getPrice());
            esModel1.setSkuImg(skuInfo.getSkuDefaultImg());
            BrandEntity brandEntity = brandService.getById(skuInfo.getBrandId());
            esModel1.setBrandName(brandEntity.getName());
            esModel1.setBrandImg(brandEntity.getLogo());
            Long catalogId = skuInfo.getCatalogId();
            CategoryEntity category = categoryService.getById(catalogId);
            esModel1.setCategoryName(category.getName());
            esModel1.setCategoryId(catalogId);
            // 设置检索属性
            esModel1.setAttrs(attrs);
            // 设置库存信息
            if(finalBooleanMap ==null){  //内部引用外面的局部变量必须加 final，保证数据的一致性
                esModel1.setHasStock(true);
            }else {
                esModel1.setHasStock(finalBooleanMap.get(skuInfo.getSkuId()));
            }
            // TODO 2.热度评分。先设为0，不写
            esModel1.setHotScore(0L);
            return esModel1;
        }).collect(Collectors.toList());
        //2、将数据发送给 es 进行保存：调用 meirimall-search（检索服务）
        R r = searchFeignService.productStatusUp(upProducts);
        if(r.getCode()==0){
            //远程调用成功，TODO 修改 spu 的状态为已上架
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            // TODO 重复调用（接口幂等性）
        }
    }

}